package cn.edu.nuc.onlinestore.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.JLabel;

import cn.edu.nuc.onlinestore.Person.ObjectStream;
import cn.edu.nuc.onlinestore.Person.User;
import cn.edu.nuc.onlinestore.frame.UserCartFrame;
import cn.edu.nuc.onlinestore.model.Goods;

public class TCPServer extends Thread {

	private User user = null;
	private String path = null;
	private ServerSocket server = null;
	ObjectInputStream ois = null;
	ObjectOutputStream oos = null;
	Socket client = null;
	InputStream in = null;
	DataInputStream dis = null;
	OutputStream out = null;
	PrintWriter dos = null;
	private JLabel label;
	private static int num;

	public TCPServer(JLabel label) {
		this.label = label;
		try {
			server = new ServerSocket(6666);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {

		while (true) {
			try {

				client = server.accept();
				// getGoods();
				in = client.getInputStream();
				out = client.getOutputStream();

				dis = new DataInputStream(in);
				dos = new PrintWriter(out);

				String msg = dis.readUTF();
				String info[] = msg.split("###");
				String result = "error";
				boolean flag = true;
				String result3 = "goodsCart";
				switch (info[0]) {

				case "register":
					File file = new File("D:/store/user/" + info[1] + ".txt");
					if (!file.exists()) {
						user = new User();
						user.setUsername(info[1]);
						user.setPassword(info[2]);
						Boolean bool = ObjectStream.Write("user/" + info[1] + ".txt", user);
						if (bool == true) {
							result = "success";
						}
					} else {
						result = "error###用户名已存在，请重新注册！";

					}
					break;

				case "login":
					user = ObjectStream.read(User.class, "user/" + info[1] + ".txt");
					if (user != null) {
						if (user.getUsername().equals(info[1]) && user.getPassword().equals(info[2])) {

							result = "success";
							num++;
							label.setText("当前在线用户数: " + num);
						} else {
							result = "error###用户名或密码错误！";
						}
					} else {
						result = "您不是会员，请注册！";
					}
					break;

				case "allgoods":

					oos = new ObjectOutputStream(out);
					List<Goods> alllist = new ArrayList<Goods>();

					File dir1 = new File("D:/store/goods");
					String[] fileStr = dir1.list();
					// int FileNum1 = dir1.list().length + 1;
					String path1;
					Goods goods1;
					int no = 0;
					for (String str : fileStr) {
						File goodsName = new File(dir1, str);
						// path1 = "goods/" + (i + 1) + ".txt";
						goods1 = ObjectStream.read(Goods.class, "goods/" + goodsName.getName());

						alllist.add(no, new Goods(goods1.getGid(), goods1.getGoodsName(), goods1.getPrice(),
								goods1.getAmount()));
						no++;

					}
					oos.writeObject(alllist);
					oos.close();
					break;

				case "allCartgoods":

					oos = new ObjectOutputStream(out);
					HashSet<Goods> allCartlist = new HashSet<Goods>();

					File dir2 = new File("D:/store/user/userCart/" + info[1]);
					String[] str = dir2.list();

					String path2 = "user/userCart/" + info[1] + "/";
					String goodName;

					for (String fileName : str) {

						File f = new File("D:/store/user/userCart/" + info[1] + "/", fileName);
						if (f.isDirectory()) {

						} else {
							goodName = f.getName();
							System.out.println("" + goodName);
							Goods good = (Goods) ObjectStream.read(Goods.class, path2 + goodName);
							System.out.println(good.toString());
							allCartlist.add(good);

						}
					}
					/*allCartlist.forEach((good) -> {
						System.out.println("TCPSever --->");
						System.out.println(good.getGoodsName());
						System.out.println(good.getGid());
						System.out.println(good.getPrice());
						System.out.println(good.getAmount());
					});*/
					oos.writeObject(allCartlist);
					oos.close();
					break;

				case "search":

					oos = new ObjectOutputStream(out);
					HashSet<Goods> allSearchlist = new HashSet<Goods>();

					File dir = new File("D:/store/goods");
					String[] strFile = dir.list();
					// System.out.println(info[0]);
					// String searchNameInfo=info[1];
					// System.out.print(searchNameInfo);

					/*
					 * String searchString=info[1].split(" "); int
					 * No=searchString.length; System.out.print(searchString);
					 */

					if (info.length == 1) {
						for (String string : strFile) {
							File GoodsName = new File(dir, string);
							Goods allGoods = ObjectStream.read(Goods.class, "goods/" + GoodsName.getName());
							allSearchlist.add(allGoods);
						}

					} else if (info[1].length() == 1) {

						for (String string : strFile) {
							File GoodsName = new File(dir, string);
							Goods goods = ObjectStream.read(Goods.class, "goods/" + GoodsName.getName());

							if (info[1].equals(goods.getGoodsName().substring(0, 1))) {

								allSearchlist.add(goods);

								continue;
							}
						}

					} else if (info[1].split(" ").length > 0) {

						String[] searchName = info[1].split(" ");
						int searchLen = searchName.length;
						for (int i = 0; i < searchLen; i++) {
							for (String string : strFile) {

								File GoodsName = new File(dir, string);
								Goods goods = ObjectStream.read(Goods.class, "goods/" + GoodsName.getName());

								if (searchName[i].equals(goods.getGoodsName())) {

									allSearchlist.add(goods);

									continue;
								}
							}
						}

					}

					oos.writeObject(allSearchlist);
					oos.close();
					break;

				case "AllGoods":
					if ("showAllGoods".equals(info[1])) {
						result = "success";
					}
					break;

				case "GoodsDetail":

					File dir4 = new File("D:/store/goods");
					int FileNum4 = dir4.list().length + 1;
					String path4;
					Goods goods4;

					for (int i = 0; i < FileNum4; i++) {

						path4 = "goods/" + info[1];
						goods4 = ObjectStream.read(Goods.class, path4);
						if (String.valueOf(goods4.getGid()).equals(info[1])) {
							result = goods4.getGid() + "###" + goods4.getGoodsName() + "###" + goods4.getPrice() + "###"
									+ goods4.getBrief() + "###" + goods4.getAmount();
							break;
						}

					}

					break;

				case "buy":

					int cou = 0;
					int count = Integer.parseInt(info[2]);

					path = "goods/" + info[1];
					Goods goods = ObjectStream.read(Goods.class, path);

					if (goods.getAmount() >= count) {

						// goods.setAmount(goods.getAmount() - count);
						// boolean boo = ObjectStream.Write(path, goods);

						// if (boo == true) {
						File fff = new File("D:/store/user/userCart/" + info[3]);

						// File dir2 = new
						// File("D:/store/user/userCart/"+info[1]);
						String[] str2 = fff.list();

						String path3 = "D:/store/user/userCart/" + info[3] + "/";
						String goodName1;
						Goods goods2 = null;
						Goods goods3 = null;

						goods2 = ObjectStream.read(Goods.class, "/user/userCart/" + info[3] + "/" + info[1]);

						if (goods2 != null) {
							goods2.setAmount(goods2.getAmount() + count);
							cou = cou + count;
							boolean bool = ObjectStream.Write("user/userCart/" + info[3] + "/" + info[1], goods2);
							if (bool != true) {
								result = "error";
							}
							result = "success###" + String.valueOf(cou);
						} else if (goods2 == null) {
							goods3 = ObjectStream.read(Goods.class, "goods/" + info[1]);
							goods3.setAmount(count);
							// goods2.setAmount(count);
							cou = cou + count;
							boolean bool = ObjectStream.Write("user/userCart/" + info[3] + "/" + info[1], goods3);
							if (bool != true) {
								result = "error";
							}
							result = "success###" + String.valueOf(cou);
						}

						// }
					} else {
						result = "库存不足！";
					}
					break;

				case "checkMoney":
					File Dir = new File("D:/store/user/userCart/" + info[1]);

					String[] strfile = Dir.list();

					for (String string : strfile) {

						File GoodsName = new File(Dir, string);
						// 读出用户购物车的商品
						Goods allGoods = ObjectStream.read(Goods.class,
								"user/userCart/" + info[1] + "/" + GoodsName.getName());
						// 在库里读出该商品
						Goods good = ObjectStream.read(Goods.class, "goods/" + GoodsName.getName());
						// 进行库存修改
						good.setAmount(good.getAmount() - allGoods.getAmount());

						boolean boo = ObjectStream.Write("goods/" + GoodsName.getName(), good);
						if (boo == true) {
							result = "success";
							GoodsName.delete();
						} else {
							result = "error";
						}
					}

					break;

				case "close":
					num--;
					label.setText("当前在线用户数: " + num);

				}

				dos.println(result);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (dos != null)
						dos.close();
					if (out != null)
						out.close();
					if (dis != null)
						dis.close();
					if (in != null)
						in.close();
					if (client != null)
						client.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

}
